const auth = require('./auth');

const request = async (promise, loading = false, config) => {
    return new Promise(async (resolve, reject) => {
        const env = config.env;
        if (!['produce', 'dev', 'host'].includes(env)) {
            wx.showToast({ title: "环境异常", icon: 'none' });
            return reject("环境异常");
        }

        const doRequest = async (retry = false) => {
            let token = wx.getStorageSync('token');
            if (!token) {
                try {
                    token = await auth.login(config); // 自动静默登录
                } catch (e) {
                    wx.showToast({ title: '自动登录失败', icon: 'none' });
                    return reject(e);
                }
            }

            const header = {
                ...config.api.header,
                ...(promise.header || {}),
                Authorization: `Bearer ${token}`
            };

            if (loading) wx.showLoading({ title: '请求中', mask: true });

            wx.request({
                url: config.api[env].url + promise.url,
                method: promise.method || 'GET',
                header,
                data: promise.data,
                success: async res => {
                    const code = res.statusCode;
                    const dataCode = res.data.code;

                    // 假设后端返回 401 或 code === 10001 表示 token 过期
                    if ((code === 401 || dataCode === 401 || dataCode === 10001) && !retry) {
                        wx.removeStorageSync('token');
                        try {
                            await auth.login(config);
                            return doRequest(true); // 重试一次
                        } catch (e) {
                            wx.showToast({ title: '重新登录失败', icon: 'none' });
                            return reject(e);
                        }
                    }

                    if (code === 200) {
                        resolve(res.data);
                    } else {
                        wx.showToast({ title: res.data.message || '请求错误', icon: 'none' });
                        reject(res.data);
                    }
                },
                fail: err => {
                    wx.showToast({ title: "网络异常", icon: 'none' });
                    reject(err);
                },
                complete: () => {
                    if (loading) wx.hideLoading();
                }
            });
        };

        await doRequest(); // 第一次调用
    });
};

module.exports = {
    request
};
